/*
 * WMLProxyEdit.java
 *
 * Created on July 3, 2001, 2:55 PM
 */

package edu.berkeley.guir.webquilt.proxy;

import java.io.*;
import java.util.*;
import com.arthurdo.parser.*;
import edu.berkeley.guir.webquilt.*;

/**
 * WebQuilt class to edit WML to redirect links, etc through the proxy.
 *
 * <P>
 * This software is distributed under the
 * <A HREF="http://guir.cs.berkeley.edu/projects/COPYRIGHT.txt">
 * Berkeley Software License</A>.
 *
 * <PRE>
 * Revisions:  - WebQuilt-v1.0-1.0.0, Jul 1 2001, Tara
 *               Created class using HtmlProxyEdit
 *             - WebQuilt Jan 15 2002, kaow
 *               Rewrote class so it inherits from ProxyEdit. Cleaned out HTML-
 *               specific stuff.
 *             - WebQuilt Apr 15 2002, kaow
 *               Added support for interdeck WAP tracking and logging
 * </PRE>
 *
 * This class utilizes the HtmlStreamTokenizer package from Arthur Do Consulting.<BR>
 *
 * @author  Wayne Kao (
 *          <A HREF="mailto:kaow@cs.berkeley.edu">kaow@cs.berkeley.edu</A>
 *          )
 * @author  Tara Williams
 * @since   JDK 1.3
 * @version WebQuilt-v1.0.0-2.0.1, Jan 15 2002
 *
 */
public class WMLProxyEdit extends ProxyEdit {

    // WMLProxyEdit constants
    public static final String TAG_A      = "a";
    public static final String TAG_GO     = "go";
    public static final String TAG_IMG    = "img";
    public static final String TAG_META   = "meta";



    /**
     * ProxyEdit constructor.
     * @param strSvr the insecure server + URI of the proxy
     * @param strSSvr the secure server + URI of the proxy
     */
    public WMLProxyEdit(String server, String secureServer) {
	super(server, secureServer);
    }

    /**
     * Toggles 'sync' debugging option. This method does
     *  nothing if this.debug = false.
     * @param sync the set sync value
     */
    public void setSync(boolean sync) {
//	if ( !debug ) { return; }

//	WMLDebugBodyEditor e = (WMLDebugBodyEditor)editors.get("card");
//	e.setSync(sync);
    }


    /**
     * Takes an input stream and edits the document so that links are
     *  redirected to the proxy server. It outputs the edited WML
     *  to the specified output stream.
     * @param istream the input stream
     * @param ostream the output stream to client
     */
    public void proxyCode(InputStream istream, OutputStream ostream) {
	    try {
            //System.out.println("Entering WMLProxyEdit.proxyCode()");

    	    PrintStream         out = new PrintStream(ostream);
    	    HtmlStreamTokenizer tok = new HtmlStreamTokenizer(new BufferedReader(new InputStreamReader(istream)));


    	    int type;
    	    while ( (type = tok.nextToken()) != HtmlStreamTokenizer.TT_EOF ) {
    //		out.print(tok.getWhiteSpace());

        		StringBuffer val = tok.getStringValue();

        		// token is a comment, just print it out
        		if ( type == HtmlStreamTokenizer.TT_COMMENT ) {
        		    out.print("<!-- " + val + " -->");

	    	    // token is text, just print it out
    	    	} else if ( type == HtmlStreamTokenizer.TT_TEXT ) {
        		    out.print(val);

        		// token is a tag
        		} else if ( type == HtmlStreamTokenizer.TT_TAG ) {
        		    WMLTag tag = new WMLTag();
        		    tok.parseTag(val, tag);

        		    String strTag = tag.getTagString().toLowerCase();
                    //System.out.println("Tag" + tag.getTagType());

                    // found CARD tag, handle it
		            if ( !tag.isEndTag() && tag.getTagType() == tag.T_CARD ) {
                        //System.out.println(" Card tag <" + val + ">");
			            out.print( "<" + val + ">" );

                        // insert timing code if necessary
                        // tell method whether CARD has ONTIMER attribute
                        //System.out.println("  Inserting timing code - calling proxyCard");
                        out.print( proxyCard(tok, tag.getParam(tag.P_ONTIMER) != null) );
                        //System.out.println("  Exiting proxyCard");

                    // editable openning tag found
                    } else if ( !tag.isEndTag() && editors.containsKey(strTag) ) {

            			WMLAbstractEditor tagEdit = (WMLAbstractEditor)editors.get(strTag);
            			String    newTag  = tagEdit.editTag(tag);
            			out.print(newTag);
                        //System.out.println(" Editable tag");

    	    	    // pass the tag along
                    } else {
        	    		out.print("<" + val + ">");
                        //System.out.println(" Else <" + val + ">" );
        		    }
        		}
    	    }
    	    out.close();

        } catch ( Exception e ) {
    	    System.err.println("Caught exception " + e);
    	    e.printStackTrace();
    	}
    } //
    /**
     * Parses the CARD contents of a WML doc
     * Finds the proper place to insert timing code
     * @param tok the HTML stream tokenizer
     * @param timerHit whether we already hit timing code in which case we
     *  don't insert ours in this card (usually false)
     * @return a string buffer full of proxied html
     */
    public StringBuffer proxyCard (HtmlStreamTokenizer tok, boolean timerHit)
                            throws IOException, HtmlException {

        //System.out.println("  Entering proxyCard");

        // reset link numbers within cards
        WMLGoLinkEditor.curLink = 0;

    	StringBuffer buf = new StringBuffer();
        boolean insideOnevent = false;  // scanning inside an ONEVENT tag

    	int type;
    	while ( (type = tok.nextToken()) != HtmlStreamTokenizer.TT_EOF ) {
    //	    buf.append(tok.getWhiteSpace());

    	    StringBuffer val = tok.getStringValue();

    	    // token is a comment, just print it out
    	    if ( type == HtmlStreamTokenizer.TT_COMMENT ) {
    		buf.append("<!-- " + val + " -->");

    	    // token is text, just print it out
    	    } else if ( type == HtmlStreamTokenizer.TT_TEXT ) {
    		buf.append(val);

    	    // token is an HTML tag
    	    } else if ( type == HtmlStreamTokenizer.TT_TAG ) {
        		WMLTag tag = new WMLTag(); tok.parseTag(val, tag);

        		String strTag = tag.getTagString().toLowerCase();
                //System.out.println("Tag:" + val);
                //System.out.println("timerHit:" + timerHit + " ; insideOnevent:" + insideOnevent);

                // it's an onevent tag
    	    	if ( !tag.isEndTag() && tag.getTagType() == tag.T_ONEVENT ) {

                    insideOnevent = true;

                    //System.out.println(" Onevent tag");
                    // has an ontimer param already
                    if (!timerHit && tag.getParam(tag.P_TYPE).trim().equalsIgnoreCase("ontimer") ) {
                        //System.out.println("  Has type=ontime");
                        timerHit = true;
                    }

        		    buf.append("<" + val + ">");

                // closing onevent tag
        		} else if ( tag.isEndTag() && tag.getTagType() == tag.T_ONEVENT ) {
                    //System.out.println(" Closing onevent tag");
        		    buf.append("<" + val + ">");
                    insideOnevent = false;

                // it's a timer tag
    	    	} else if ( !timerHit && !tag.isEndTag() && tag.getTagType() == tag.T_TIMER ) {

                    //System.out.println(" timer tag");
        		    buf.append("<" + val + ">");
                    timerHit = true;

        		// found closing </CARD> tag
                // let's finish up
        		} else if ( tag.isEndTag() && tag.getTagType() == tag.T_CARD) {
                    //System.out.println(" /card tag");
        		    return buf.append("<" + val + ">");

                // hitting any other tag or editable
                } else if (! insideOnevent || (!tag.isEndTag() && editors.containsKey(strTag) )) {
                    //System.out.println(" Other tag or editable");

                    if (!timerHit && !insideOnevent) {
                        //System.out.println("  Other tag outside onevent");
                        buf.append("<onevent type=\"ontimer\">\n<go href=\"testpages/wq_interdeck.wmls#addOne()\" />\n</onevent>\n<timer value=\"10\"/>");
                        timerHit = true;
                    }

                    // editable
                    if ( !tag.isEndTag() && editors.containsKey(strTag) ) {
                        //System.out.println("  Editable");
            		    // process tag
            		    WMLAbstractEditor tagEdit = (WMLAbstractEditor)editors.get(strTag);
            		    String    newTag  = tagEdit.editTag(tag);
            		    buf.append(newTag);

                    } else {
                        buf.append("<" + val + ">");
                    }

        		} else {
        		    // pass the tag along
        		    buf.append("<" + val + ">");
        		}
    	    }
    	}

	    // never encountered closing </CARD> tag
        return buf;

    } //


} // of class
//==============================================================================

/*
Copyright (c) 2001 Regents of the University of California.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.

3. All advertising materials mentioning features or use of this software
   must display the following acknowledgement:

      This product includes software developed by the Group for User
      Interface Research at the University of California at Berkeley.

4. The name of the University may not be used to endorse or promote products
   derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
*/
